package com.dingpeikeji.quickdeer.modules.rentproduct.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.service.CrudService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.modules.rentproduct.dao.RentproductProcedureDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.dao.TRentprodModifyDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProCmptPeriod;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentprodModify;

/**
 * 整车价格修改Service
 * @author wuhao
 * @version 2016-08-08
 */
@Service
@Transactional(readOnly = true)
public class TRentprodModifyService extends CrudService<TRentprodModifyDao, TRentprodModify> {

	@Autowired
	private RentproductProcedureDao rentproductProcedureDao;
	
	public TRentprodModify get(String rentchgid) {
		return super.get(rentchgid);
	}
	
	public List<TRentprodModify> findList(TRentprodModify tRentprodModify) {
		return super.findList(tRentprodModify);
	}
	
	public Page<TRentprodModify> findPage(Page<TRentprodModify> page, TRentprodModify tRentprodModify) {
		return super.findPage(page, tRentprodModify);
	}
	
	@Transactional(readOnly = false)
	public void save(TRentprodModify tRentprodModify) throws RuntimeException {
		if(tRentprodModify.getRentchgid() == null){
			tRentprodModify.setCreateBy(UserUtils.getUser());
			tRentprodModify.setCreateDate(new Date());
			dao.insert(tRentprodModify);
		} else {
			dao.update(tRentprodModify);
		}
		// 每次的整车调整都生成一次价格区间
		ProCmptPeriod pro = new ProCmptPeriod();
		pro.setForsaleid(tRentprodModify.getForsaleid());
		pro.setSuitrtnprice(tRentprodModify.getSuitrtnprice());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		pro.setEfftdate(sdf.format(tRentprodModify.getEfftdate()));
		pro.setInvaliddate(sdf.format(tRentprodModify.getInvaliddate()));
		rentproductProcedureDao.proCmptPeriod(pro.toMap().getParam());
		Integer returnflag = (Integer) pro.getParam().get("returnflag");
		if(returnflag==null||returnflag!=0){
			logger.debug("价格区间调整失败={}",(String) pro.getParam().get("returnmsg"));
			throw new RuntimeException((String) pro.getParam().get("returnmsg"));
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(TRentprodModify tRentprodModify) {
		super.delete(tRentprodModify);
	}
	
}